package com.mf.morefun.ui.person.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusFragment;
import com.mf.morefun.bean.AddressBean;
import com.mf.morefun.bean.AliInfoBean;
import com.mf.morefun.bean.BirthBean;
import com.mf.morefun.bean.ClassBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.NameBean;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.PasswordBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestAddressBean;
import com.mf.morefun.requestbean.RequestBirthBean;
import com.mf.morefun.requestbean.RequestChangeHeadBean;
import com.mf.morefun.requestbean.RequestClassBean;
import com.mf.morefun.requestbean.RequestEnableTImeBean;
import com.mf.morefun.requestbean.RequestNameBean;
import com.mf.morefun.requestbean.RequestPasswordBean;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.moreread.TestActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.StorageUtil;
import com.mf.morefun.util.UploadUtil;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.mf.morefun.widget.TransformationPersonUtils;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DatePicker;

import static android.app.Activity.RESULT_OK;
import static android.support.constraint.Constraints.TAG;

public class PersonFraagment extends BaseBusFragment {

    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_password)
    TextView tvPassword;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_birth)
    TextView tvBirth;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    private PopupWindow mHeadPop = null;
    private PopupWindow mNamePop = null;
    private PopupWindow mAddressPop = null;
    private SPUtils mSputils;
    private int selectYear = 0;
    private int selectMonth = 0;
    private int selectDay = 0;
    private int mYear = 2019;
    private int mMonth = 3;
    private int mDay = 18;
    private int selectEnableYear = 0;
    private int selectEnableMonth = 0;
    private int selectEnableDay = 0;
    private RoundProcessDialog dialog;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_person;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mSputils = new SPUtils(getActivity());
        EventBus.getDefault().register(this);
        dialog = new RoundProcessDialog(getActivity(), "正在上传中...");
        if (!IsLoginBean.isNo(false)){
            GetUserInfo.initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
        }else {
            initGetData();
        }

        initGetAliInfo();
    }

    private void initGetAliInfo() {
        RequestParams params = new RequestParams(com.mf.morefun.constant.Configuration.HOST + com.mf.morefun.constant.Configuration.GETALIINFOV2);

        PMUserBean.CountryBean countrybean = new PMUserBean.CountryBean();
        countrybean.setId( MoreFunApplication.loginBean.getResult().getCountry().getId());
        params.setBodyContent(JSON.toJSONString(countrybean));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AliInfoBean aliInfoBean = JSON.parseObject(result, AliInfoBean.class);
                    if (aliInfoBean.getStatusCode() == 200) {
                        mSputils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYID, aliInfoBean.getAccessKeyId());
                        mSputils.putString(com.mf.morefun.constant.Configuration.ACCESSKEYSECRET, aliInfoBean.getAccessKeySecret());
                        mSputils.putString(com.mf.morefun.constant.Configuration.SECURITYTOKEN, aliInfoBean.getSecurityToken());

                        mSputils.putString(com.mf.morefun.constant.Configuration.ENDPOINT, aliInfoBean.getEndPoint());
                        mSputils.putString(com.mf.morefun.constant.Configuration.BUCKETNAME, aliInfoBean.getBucketName());
                        mSputils.putString(com.mf.morefun.constant.Configuration.BUCKETDOMAIN, aliInfoBean.getBucketDomain());
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void  initGetData(){
        showCicleImg("");//头像
        tvName.setText(MoreFunApplication.loginBean.getResult().getName());
        tvPhone.setText(MoreFunApplication.loginBean.getResult().getPhone());
        if (null != MoreFunApplication.loginBean.getResult().getCity()){
            tvCity.setText(MoreFunApplication.loginBean.getResult().getCity().getName());
        }else {
            tvCity.setText("无");
        }
        if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getAddress())){
            tvAddress.setText("请点击添加地址");
        }else {
            tvAddress.setText(MoreFunApplication.loginBean.getResult().getAddress());
        }
        if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getBirthday())){
            tvBirth.setText(DateUtils.DATE_YEAR_MONTH_DAY.format(new Date(System.currentTimeMillis())));
        }else {
            tvBirth.setText(MoreFunApplication.loginBean.getResult().getBirthday());
        }
        if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getBirthday())){
            tvTime.setText(DateUtils.DATE_YEAR_MONTH_DAY.format(new Date(System.currentTimeMillis())));
        }else {
            try {
                if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getEnableEnd())) {
                    tvTime.setText("");
                } else {
                    if (MoreFunApplication.loginBean.getResult().getEnableEnd().length() == 10) {
                        tvTime.setText(MoreFunApplication.loginBean.getResult().getEnableEnd());
                    } else {
                        long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(MoreFunApplication.loginBean.getResult().getEnableEnd()).getTime();
                        tvTime.setText(DateUtils.DATE_YEAR_MONTH_DAY.format(new Date(enableTime)));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                tvTime.setText("");
            }
        }
        mYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        mMonth = Integer.parseInt(new SimpleDateFormat("MM").format(new Date(System.currentTimeMillis())));
        mDay = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(System.currentTimeMillis())));
        String birthDay = MoreFunApplication.loginBean.getResult().getBirthday();
        if (StringUtils.isEmpty(birthDay)){
            selectYear = mYear;
            selectMonth = mMonth;
            selectDay = mDay;
        }else {
            String birth[] = birthDay.split("-");
            try {
                if (birth.length == 3) {
                    selectYear = Integer.parseInt(birth[0]);
                    selectMonth = Integer.parseInt(birth[1]);
                    selectDay = Integer.parseInt(birth[2]);
                } else {
                    selectYear = mYear;
                    selectMonth = mMonth;
                    selectDay = mDay;
                }
            } catch (Exception e) {
                e.printStackTrace();
                selectYear = mYear;
                selectMonth = mMonth;
                selectDay = mDay;
            }
        }
        String enableEnd = MoreFunApplication.loginBean.getResult().getEnableEnd();
        if (StringUtils.isEmpty(enableEnd)){
            selectEnableYear = mYear;
            selectEnableMonth = mMonth;
            selectEnableDay = mDay;
        }else {
            String enable[] = enableEnd.split("-");
            try {
                if (enable.length == 3) {
                    selectEnableYear = Integer.parseInt(enable[0]);
                    selectEnableMonth = Integer.parseInt(enable[1]);
                    selectEnableDay = Integer.parseInt(enable[2]);
                } else {
                    selectEnableYear = mYear;
                    selectEnableMonth = mMonth;
                    selectEnableDay = mDay;
                }
            } catch (Exception e) {
                e.printStackTrace();
                selectEnableYear = mYear;
                selectEnableMonth = mMonth;
                selectEnableDay = mDay;
            }
        }
        if (MoreFunApplication.loginBean.getResult().getUserType().equals("3")){
            tvClass.setVisibility(View.INVISIBLE);
        }else {
            initClass();
        }
    }

    private void initClass() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.QUERYCLASS);
        RequestClassBean requestClassBean = new RequestClassBean();
        RequestClassBean.UserBean userBean = new RequestClassBean.UserBean();
        userBean.setId(mSputils.getString(Configuration.USERID));
        requestClassBean.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestClassBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ClassBean classBean = JSON.parseObject(result, ClassBean.class);
                    if (classBean.getErrorCode() == 0) {
                        if (null != classBean.getResult() && classBean.getResult().size() > 0){
                            String className = "";
                            if (null != classBean.getResult() && classBean.getResult().size() > 0){
                                className = className + ";" + classBean.getResult().get(0).getClassBelong().getName();
                            }
                            tvClass.setText(className.substring(1));
                        }else {
                            tvClass.setText("无");
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    CircleCrop circleCrop = new CircleCrop();
                    RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                    Glide.with(getActivity()).asBitmap().load(R.mipmap.mine_user_head).apply(options).into(new TransformationPersonUtils((ImageView)msg.obj, getActivity()));
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(getActivity());
                    errorPop.showPop("");
                    break;
            }
        }
    };

    private class mRequestListener implements RequestListener {
        private ImageView ivPersonhead;
        public mRequestListener (ImageView ivPersonhead){
            this.ivPersonhead = ivPersonhead;
        }
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString()+"  model:"+model+" isFirstResource: "+isFirstResource);
            Message msg = new Message();
            msg.what = 100;
            msg.obj = ivPersonhead;
            mHandler.sendMessage(msg);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG,  "model:"+model+" isFirstResource: "+isFirstResource);
            return false;
        }
    };

    private void showCicleImg(String url) {
        CircleCrop circleCrop = new CircleCrop();
        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
        if (StringUtils.isEmpty(url)){
            Glide.with(getActivity()).asBitmap().load(MoreFunApplication.loginBean.getResult().getHeadPortrait()).listener(new mRequestListener(ivHead)).apply(options).into(new TransformationPersonUtils(ivHead, getActivity()));
        }else {
            Glide.with(getActivity()).asBitmap().load(new File(url)).listener(new mRequestListener(ivHead)).apply(options).into(new TransformationPersonUtils(ivHead, getActivity()));
        }
    }

    @Override
    protected void initData() {

    }

    //修改头像

    /**
     * 显示底部栏
     */
    private void showChangeHead() {
        closePop();
        if (mHeadPop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_pophead, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_camara = (TextView) view.findViewById(R.id.tv_camara);
            tv_camara.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (StorageUtil.camearaUtil(getActivity())){
                        CallSystemCamera();
                    }else {
                        showMissingPermissionDialog();
                    }
                    closePop();
                }
            });
            TextView tv_bendi = (TextView) view.findViewById(R.id.tv_bendi);
            tv_bendi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    CallSystemPhoto();
                    closePop();
                }
            });
            TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    closePop();
                }
            });
            int h = getActivity().getWindowManager().getDefaultDisplay().getHeight();
            mHeadPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            mHeadPop.setFocusable(true);
            mHeadPop.setOutsideTouchable(true);
            mHeadPop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            mHeadPop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = getActivity().getWindow().getDecorView().getHeight();
            mHeadPop.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private String mFilePath;

    //调用系统相机
    private void CallSystemCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android自带的照相机
            long time = System.currentTimeMillis();
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            mFilePath = Environment.getExternalStorageDirectory() + "/" + sdf.format(date) + ".jpg";
            // 加载路径
            Uri uri = Uri.fromFile(new File(mFilePath));
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            // 指定存储路径，这样就可以保存原图了
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 1);
        }catch (Exception e){
            e.printStackTrace();
            //直接申请权限
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startAppSettings();
            }
        });

        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getActivity().getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getActivity().getPackageName());
        }
        getActivity().startActivity(localIntent);
    }


    //调用本地相册
    private void CallSystemPhoto() {
        try {
            Intent intent = null;
            if (DeviceUtils.getPhoneBrand().contains("meizu")) {
                intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
            }
            startActivityForResult(intent, 2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                options.inSampleSize = 10;
//				 把流解析成bitmap
                Bitmap bitmap = BitmapFactory.decodeFile(mFilePath, options);
//                mUserdetailUserheader.setImageBitmap(bitmap);
                File file = new File(mFilePath);
                String path = file.getAbsolutePath();
                showCicleImg(path);
                if (null != dialog && !dialog.isShow()){
                    dialog.show();
                }
                UploadUtil uploadUtil = new UploadUtil();
                uploadUtil.uploadFile(getActivity(),
                        mSputils.getString(Configuration.ACCESSKEYID),
                        mSputils.getString(Configuration.ACCESSKEYSECRET),
                        mSputils.getString(Configuration.SECURITYTOKEN),
                        mSputils.getString(Configuration.ENDPOINT),
                        mSputils.getString(Configuration.BUCKETNAME),
                        System.currentTimeMillis() + "androidimg.jpg",
                        path, false);
            } else if (requestCode == 2) {
                if (data != null) {
                    Uri uri = data.getData();
                    String path = "";
                    if (!TextUtils.isEmpty(uri.getAuthority())) {
                        Cursor cursor = getActivity().getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                        if (null == cursor) {
                            ToastUtils.show(getActivity(), "", ToastUtils.LENGTH_SHORT);
                            return;
                        }
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        options.inSampleSize = 10;
//						 把流解析成bitmap
                        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                        cursor.close();
                        showCicleImg(path);
                        if (null != dialog && !dialog.isShow()){
                            dialog.show();
                        }
                        //上传文件
                        UploadUtil uploadUtil = new UploadUtil();
                        uploadUtil.uploadFile(getActivity(),
                                mSputils.getString(Configuration.ACCESSKEYID),
                                mSputils.getString(Configuration.ACCESSKEYSECRET),
                                mSputils.getString(Configuration.SECURITYTOKEN),
                                mSputils.getString(Configuration.ENDPOINT),
                                mSputils.getString(Configuration.BUCKETNAME),
                                System.currentTimeMillis() + "androidimg.jpg",
                                path, false);
                    }
                }
            }
        }
    }

    //接受RecordMusicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if(message.getType() == 101){
           // String host = Configuration.OOSROOT; //"http://morefunreadingproduct.oss-cn-shanghai.aliyuncs.com/";

            String host =  mSputils.getString(Configuration.BUCKETDOMAIN);

            //开始上传
            initSaveImg(host + message.getFileName());
        }else if(message.getType() == 102){
            ToastUtils.show(getActivity(), "上传失败", 100);
        }
        if (null != dialog && dialog.isShow()){
            dialog.cancel();
        }
    }

    private void initSaveImg(String imgUrl) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEHEAD);
        RequestChangeHeadBean requestChangeHeadBean = new RequestChangeHeadBean();
        requestChangeHeadBean.setId(mSputils.getString(Configuration.USERID));
        requestChangeHeadBean.setHeadPortrait(imgUrl);
        params.setBodyContent(JSON.toJSONString(requestChangeHeadBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        MoreFunApplication.loginBean.getResult().setHeadPortrait(imgUrl);
                    }else {
                        ToastUtils.show(getActivity(), resultBean.getMessage(),100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //关闭pop
    private void closePop() {
        if (null != mHeadPop) {
            mHeadPop.dismiss();
            mHeadPop = null;
        }
        if (null != mNamePop) {
            mNamePop.dismiss();
            mNamePop = null;
        }
        if (null != mAddressPop) {
            mAddressPop.dismiss();
            mAddressPop = null;
        }
    }

    @OnClick({R.id.rl_head, R.id.tv_name, R.id.tv_password, R.id.tv_city, R.id.tv_time, R.id.tv_phone, R.id.tv_birth, R.id.tv_class, R.id.tv_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_head:
                try {
                    showChangeHead();
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
            case R.id.tv_name:
                showChangeName(0, tvName.getText().toString());
                break;
            case R.id.tv_password:
                showChangeName(1, "");
                break;
            case R.id.tv_city://暂时没借口
                break;
            case R.id.tv_time:
                break;
            case R.id.tv_phone:
                break;
            case R.id.tv_birth:
                DatePicker pickerBirth = new DatePicker(getActivity(), DatePicker.YEAR_MONTH_DAY);
                pickerBirth.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
                pickerBirth.setRangeStart(1900, 1, 1);
                pickerBirth.setRangeEnd(mYear, mMonth, mDay);
                pickerBirth.setSelectedItem(selectYear, selectMonth, selectDay);
                pickerBirth.setLineVisible(true);
                pickerBirth.setCanLoop(false);
                pickerBirth.setWeightEnable(true);
                pickerBirth.setLineColor(0xfff0f0f0);
                pickerBirth.setTopPadding(10);
                pickerBirth.setSubmitTextColor(Color.parseColor("#00CC99"));
                pickerBirth.setSelectedTextColor(Color.parseColor("#333333"));
                LineConfig lineConfigBirth = new LineConfig();
                lineConfigBirth.setColor(Color.parseColor("#eaeaea"));
                pickerBirth.setLineConfig(lineConfigBirth);
                pickerBirth.setCanLinkage(true);
                pickerBirth.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        String birth = year + "-" + month + "-" + day;
                        initChangeBirth(birth);
                    }
                });
                pickerBirth.show();
                break;
            case R.id.tv_class:
                break;
            case R.id.tv_address:
                try {
                    showChangeAddress();
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
        }
    }

    private void initChangeTime(String time) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SETTIMEENABLE);
        RequestEnableTImeBean requestEnableTImeBean = new RequestEnableTImeBean();
        requestEnableTImeBean.setEnableEnd(time);
        requestEnableTImeBean.setId(mSputils.getString(Configuration.USERID));
        params.setBodyContent(JSON.toJSONString(requestEnableTImeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        //这里说明修改成功了
                        MoreFunApplication.loginBean.getResult().setEnableEnd(time);
                        tvTime.setText(time);
                    }else {
                        ToastUtils.show(getActivity(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void showChangeAddress() {
        closePop();
        if (null == mAddressPop) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_popaddress, null);
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                }
            });
            EditText edit_address = view.findViewById(R.id.edit_address);
            edit_address.setText(MoreFunApplication.loginBean.getResult().getAddress());
            TextView tv_sure = view.findViewById(R.id.tv_sure);
            tv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtils.isEmpty(edit_address.getText().toString())) {
                        ToastUtils.show(getActivity(), "请输入地址", 100);
                        return;
                    }
                    initChangeAddress(edit_address.getText().toString());
                    closePop();
                }
            });
            mAddressPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mAddressPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mAddressPop.setBackgroundDrawable(new BitmapDrawable());
            mAddressPop.setFocusable(true);
            mAddressPop.update();
            mAddressPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mAddressPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mAddressPop.dismiss();
                    mAddressPop = null;
                }
            });
        }
    }

    private void initChangeAddress(String address) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEADDRESS);
        RequestAddressBean requestAddressBean = new RequestAddressBean();
        requestAddressBean.setId(mSputils.getString(Configuration.USERID));
        requestAddressBean.setAddress(address);
        params.setBodyContent(JSON.toJSONString(requestAddressBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    AddressBean addressBean = JSON.parseObject(result, AddressBean.class);
                    if (addressBean.getErrorCode() == 0){
                        tvAddress.setText(address);
                        MoreFunApplication.loginBean.getResult().setAddress(address);
                    }else {
                        ToastUtils.show(getActivity(), addressBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initChangeBirth(String birth) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEBIRTHDAY);
        RequestBirthBean requestBirthBean = new RequestBirthBean();
        requestBirthBean.setId(mSputils.getString(Configuration.USERID));
        requestBirthBean.setBirthday(birth + " 20:30:59");
        params.setBodyContent(JSON.toJSONString(requestBirthBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    BirthBean birthBean = JSON.parseObject(result, BirthBean.class);
                    if (birthBean.getErrorCode() == 0) {
                        tvBirth.setText(birth);
                        MoreFunApplication.loginBean.getResult().setBirthday(birth);
                    } else {
                        ToastUtils.show(getActivity(), birthBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //改名字
    private void showChangeName(int index, String name) {
        try {
            closePop();
            if (null == mNamePop) {
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.layout_popname, null);
                // 这里启动头像
                RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
                rl_bg.getBackground().setAlpha(100);
                EditText edit_name = view.findViewById(R.id.edit_name);
                edit_name.setText(name);
                if (index == 0) {
                    edit_name.setHint("请输入您的昵称");
                } else {
                    edit_name.setHint("请输入您的密码");
                }
                TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closePop();
                    }
                });
                TextView tv_sure = view.findViewById(R.id.tv_sure);
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (index == 0) {
                            if (StringUtils.isEmpty(edit_name.getText().toString())) {
                                ToastUtils.show(getActivity(), "请输入昵称", 100);
                                return;
                            }
                            //这里调接口
                            initChangeName(edit_name.getText().toString());
                        } else {
                            if (StringUtils.isEmpty(edit_name.getText().toString())) {
                                ToastUtils.show(getActivity(), "请输入密码", 100);
                                return;
                            }
                            if (edit_name.getText().toString().length() < 6 || edit_name.getText().toString().length() > 10) {
                                ToastUtils.show(getActivity(), "密码为6-10位数字或字母", 100);
                                return;
                            }
                            if (!StringUtils.isSurePassword(edit_name.getText().toString())) {
                                ToastUtils.show(getActivity(), "密码为6-10位数字或字母", 100);
                                return;
                            }
                            initChangePassword(edit_name.getText().toString());
                        }
                        closePop();
                    }
                });
                mNamePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                mNamePop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                mNamePop.setBackgroundDrawable(new BitmapDrawable());
                mNamePop.setFocusable(true);
                mNamePop.update();
                mNamePop.showAtLocation(view, Gravity.CENTER, 0, 0);
                mNamePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mNamePop.dismiss();
                        mNamePop = null;
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void initChangePassword(String password) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGEPASSWORD);
        RequestPasswordBean requestPasswordBean = new RequestPasswordBean();
        requestPasswordBean.setNewPassword(password);
        requestPasswordBean.setPhone(mSputils.getString(Configuration.USERPHONE));
        params.setBodyContent(JSON.toJSONString(requestPasswordBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    PasswordBean passwordBean = JSON.parseObject(result, PasswordBean.class);
                    ToastUtils.show(getActivity(), passwordBean.getMessage(), 100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //修改昵称
    private void initChangeName(String name) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.CHANGENAME);
        RequestNameBean requestNameBean = new RequestNameBean();
        requestNameBean.setId(mSputils.getString(Configuration.USERID));
        requestNameBean.setName(name);
        params.setBodyContent(JSON.toJSONString(requestNameBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    NameBean nameBean = JSON.parseObject(result, NameBean.class);
                    if (nameBean.getErrorCode() == 0) {
                        tvName.setText(name);
                        MoreFunApplication.loginBean.getResult().setName(name);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
